﻿using static Quartz.Logging.OperationName;

namespace Away.Jobs.Repositories.Models;

public class TriggerModel
{
    public string SchedName { get; set; } = null!;
    public string TriggerName { get; set; } = null!;
    public string TriggerGroup { get; set; } = null!;
    public string JobName { get; set; } = null!;
    public string JobGroup { get; set; } = null!;
    public string? Description { get; set; }
    public DateTime? NextFireTime { get; set; }
    public DateTime? PrevFireTime { get; set; }
    public int? Priority { get; set; }
    public string TriggerState { get; set; } = null!;
    public string TriggerType { get; set; } = null!;
    public DateTime StartTime { get; set; }
    public DateTime? EndTime { get; set; }
    public string? CalendarName { get; set; }
    public short? MisfireInstr { get; set; }
    public string? JobData { get; set; }
    public CronTriggerModel? QrtzCronTrigger { get; set; }
    public SimpleTriggerModel? QrtzSimpleTrigger { get; set; }
    public SimpropTriggerModel? QrtzSimpropTrigger { get; set; }
    public BlobTriggerModel? QrtzBlobTrigger { get; set; }

    [JsonIgnore]
    public TriggerKey Key => new(TriggerName, TriggerGroup);

    [JsonIgnore]
    public ITrigger Trigger
    {
        get
        {
            var trigger = TriggerBuilder.Create()
                .WithIdentity(Key)
                .ModifiedByCalendar(CalendarName)
                .WithDescription(Description)
                .ForJob(JobName, JobGroup)
                .StartAt(StartTime);

            if (EndTime.HasValue)
            {
                trigger.EndAt(EndTime);
            }
            if (Priority.HasValue)
            {
                trigger.WithPriority(Priority.Value);
            }
            if (!string.IsNullOrWhiteSpace(JobData))
            {
                var jobData = JsonSerializer.Deserialize<JobDataMap>(JobData);
                trigger.UsingJobData(jobData!);
            }
            if (QrtzCronTrigger != null)
            {
                trigger.WithCronSchedule(QrtzCronTrigger.CronExpression, o =>
                {
                    if (!string.IsNullOrWhiteSpace(QrtzCronTrigger.TimeZoneId))
                    {
                        o.InTimeZone(TimeZoneInfo.FindSystemTimeZoneById(QrtzCronTrigger.TimeZoneId));
                    }
                });
            }
            if (QrtzSimpleTrigger != null)
            {
                trigger.WithSimpleSchedule(o =>
                {
                    o.WithInterval(TimeSpan.FromMilliseconds(QrtzSimpleTrigger.RepeatInterval));
                    o.WithRepeatCount(Convert.ToInt32(QrtzSimpleTrigger.RepeatCount));
                });
            }

            return trigger.Build();
        }
    }
}
